<template>
  <div class="home">
    <van-search shape="round" background="#C82519" placeholder="请输入搜索关键词" @click="jumpToSearch" />

    <!-- 轮播图区域 -->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="image in images" :key="image.id">
        <img :src="image.imageUrl" alt="">
      </van-swipe-item>
    </van-swipe>

    <!-- grid宫格区域 -->
    <van-grid :column-num="5" :icon-size="36" :border='false'>
      <van-grid-item v-for="val in gridData" :key="val.id" :icon="val.icon" :text="val.text" />
    </van-grid>

    <!-- 倒计时区域 -->
    <van-count-down :time="countdownTime">
      <template #default="timeData">
        <h4>商品秒杀</h4>
        <div class="time">
          <span class="block">{{ timeData.hours }}</span>
          <span class="colon">:</span>
          <span class="block">{{ timeData.minutes }}</span>
          <span class="colon">:</span>
          <span class="block">{{ timeData.seconds }}</span>
        </div>
        <div class="imgs">
          <div class="imgs-item" v-for="skill in seckill" :key="skill.id">
            <img :src="skill.image" alt="">
            <div class="pirce">¥{{ skill.price }}元</div>
          </div>

        </div>
      </template>
    </van-count-down>

    <!-- 推荐商品 -->
    <van-divider>推荐商品</van-divider>
    <!-- 商品列表：无限加载 -->
    <van-list :immediate-check="false" v-model:loading="loading" :finished="finished" finished-text="没有更多了..."
      @load="loadMore">
      <van-row>
        <van-col v-for="rec in recommend" :key="rec.id">
          <div class="prod-item">
            <div class="prod-bg">
              <img :src="rec.image" alt="">
            </div>
            <div class="title">{{ rec.title }}</div>
            <div class="hot">销量{{ rec.saleNum }}</div>
            <div class="pice">
              <span>原价{{ rec.originPrice }}</span>
              <span>现价{{ rec.price }}</span>
            </div>
            <div><van-button type="danger" size="mini" @click="handleAddToCart(rec)">加入购物车</van-button></div>
          </div>
        </van-col>
      </van-row>
    </van-list>

  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
// 引入 api 接口
import { fidneHomeData, findMore } from '../../api/home'
import useCartStore from '../../store/modules/cart'

// 引入css
import { showSuccessToast } from 'vant';

import { ref } from 'vue'

const router = useRouter()

// 获取购物的 store
const store = useCartStore()

// 跳转到搜索页面
const jumpToSearch = () => {
  router.push('/search')
}

// 加载图像资源：根据图像名称，获取图像资源 URL
function getImageUrl(name: any) {
  return new URL(`../../assets/home-Img/${name}.png`, import.meta.url).href
}

// 定义九宫格中所需要用到的数据
const gridData: any = [
  {
    id: 1,
    icon: getImageUrl('g1'),
    text: '优选超市'
  },
  {
    id: 2,
    icon: getImageUrl('g2'),
    text: '数码电器'
  },
  {
    id: 3,
    icon: getImageUrl('g3'),
    text: '新百货'
  },
  {
    id: 4,
    icon: getImageUrl('g4'),
    text: '新生鲜'
  },
  {
    id: 5,
    icon: getImageUrl('g5'),
    text: '服务到家'
  },
  {
    id: 6,
    icon: getImageUrl('g6'),
    text: '充值缴费'
  },
  {
    id: 7,
    icon: getImageUrl('g7'),
    text: '附近好货'
  },
  {
    id: 8,
    icon: getImageUrl('g8'),
    text: '会员'
  },
  {
    id: 9,
    icon: getImageUrl('g9'),
    text: '国际'
  },
  {
    id: 10,
    icon: getImageUrl('g10'),
    text: '拍卖'
  },
]

// 倒计时时间（毫秒值）
const countdownTime = ref(30 * 60 * 1000)

// 轮播图数组
const images = ref<any[]>([])
// 秒杀数组
const seckill = ref<any[]>([])
// 推荐商品数组
const recommend = ref<any[]>([])

// 加载首页数据
const loadHomeData = async () => {
  const result: any = await fidneHomeData()
  console.log(result)
  images.value = result.slideshow
  seckill.value = result.seckill
  recommend.value = result.recommend
}
loadHomeData()

// 无限加载
const page = ref(1)
const loading = ref(false) // 是否正在加载中
const finished = ref(false) // 是否所有数据加载完毕
const loadMore = async () => {
  // 触底发送请求，查询更多商品数据，实现无限加载
  const result: any = await findMore({ page: page.value })
  // 将获取到的数据追加到原来的推荐商品数组中去
  recommend.value = recommend.value.concat(result.list)
  // 数据更新完毕后取消loading
  loading.value = false
  // 停止继续发送请求获取数据
  finished.value = result.isEnd
  page.value += 1
}

// 点击加入购物车
const handleAddToCart = (goods: Goods) => {
  const { id, title, image, price, saleNum } = goods
  const curr = {
    id, title, image, price, saleNum,
    amount: 1,
  }
  // 调用store中的 action 方法
  store.addToCart(curr)
  showSuccessToast('加入成功')
}

</script>

<style lang="less" scoped>
.home {
  margin-bottom: 50px;
}

.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
  height: 160px;
  position: relative;

  // background-color: #39a9ed;
  img {
    border-radius: 10px;
    width: 95%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.van-grid {
  background: #f0f0f0;
  padding: 10px 0;
  margin-bottom: 10px;

  :deep(.van-grid-item__content) {
    background: #f0f0f0;
  }
}

// 倒计时
.van-count-down {
  position: relative;
  height: 100px;

  .time {
    position: absolute;
    top: -8px;
    left: 70px;
  }

  h4 {
    position: absolute;
    top: -27px;
    left: 6px;
  }

  .imgs {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .imgs-item {
      margin-top: 18px;
    }

    .pirce {
      text-align: center;
      color: #FB4131;
      font-size: 13px;
      font-weight: 600;
    }

    img {
      width: 75px;
      height: 65px;
    }
  }
}

.colon {
  display: inline-block;
  margin: 0 4px;
  color: #1989fa;
}

.block {
  display: inline-block;
  width: 22px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background-color: #FB4131;
}

.van-row {
  padding-left: 5px;
}

.prod-item {
  width: 160px;
  height: 236px;
  position: relative;
  margin: 1px;
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  background-color: #f0f0f0;

  .prod-bg {
    width: 160px;
    height: 120px;
    margin-top: 5px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .title {
    width: 150px;
    text-align: left;
    font-family: -apple-system, Helvetica, sans-serif;
    color: #434343;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    word-break: break-all;
    -webkit-box-orient: vertical;
  }

  .pice {
    margin-top: 5px;
    width: 150px;
    display: flex;
    justify-content: space-around;

    span:nth-child(1) {
      text-decoration: line-through;
      color: #434343;
      font-size: 12px;
    }

    span:nth-child(2) {
      font-size: 13px;
      color: red;
    }
  }

  .hot {
    font-size: 13px;
    color: #c03f3f;
  }

  .van-button {
    width: 100px;
    position: absolute;
    bottom: 5px;
    left: 25%;
  }
}</style>
